//
//  Hear_AddSoundViewCell.m
//  Hear
//
//  Created by mac on 2018/4/26.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "Hear_AddSoundViewCell.h"

#import "Hear_MusicListModel.h"

@interface Hear_AddSoundViewCell()

@property (nonatomic, strong) UIImageView *coverImg;

@property (nonatomic, strong) UILabel *titleLB;

@property (nonatomic, strong) UILabel *authorLB;

@property (nonatomic, strong) UILabel *timeLB;

@property (nonatomic, strong) UIImageView *selectImg;

@property (nonatomic, strong) UIButton *playbtn;

/** 播放器 */
@property (nonatomic, strong) AVPlayer *player;

@property (nonatomic, strong) AVPlayerItem *item;

@end

@implementation Hear_AddSoundViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setupUI];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Hear_AddSoundViewControllerAction) name:@"Hear_AddSoundViewController" object:nil];
    }
    return self;
}

- (void)setupUI {
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    UIImageView *coverImg = [[UIImageView alloc] initWithImage:GetImgWithStr(@"soundcover3.jpg")];
    coverImg.contentMode = UIViewContentModeScaleAspectFit;
    coverImg.userInteractionEnabled = YES;
    self.coverImg = coverImg;
    [self.contentView addSubview:coverImg];
    
    UIButton *playbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [playbtn setImage:GetImgWithStr(@"edit_播放") forState:UIControlStateNormal];
    [playbtn addTarget:self action:@selector(playbtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.playbtn = playbtn;
    [coverImg addSubview:playbtn];
    
    UILabel *titleLB = [UILabel new];
    titleLB.font = [UIFont systemFontOfSize:14];
    titleLB.textColor = [UIColor colorWithHexString:@"#222222"];
    titleLB.textAlignment = NSTextAlignmentLeft;
    titleLB.text = @"最想去的地方";
    self.titleLB = titleLB;
    [self.contentView addSubview:titleLB];
    
    UILabel *authorLB = [UILabel new];
    authorLB.font = [UIFont systemFontOfSize:13];
    authorLB.textColor = [UIColor colorWithHexString:@"#6E6E6E"];
    authorLB.textAlignment = NSTextAlignmentLeft;
    authorLB.text = @"呵呵哒";
    self.authorLB = authorLB;
    [self.contentView addSubview:authorLB];
    
    UILabel *timeLB = [UILabel new];
    timeLB.font = [UIFont systemFontOfSize:13];
    timeLB.textColor = [UIColor colorWithHexString:@"#6E6E6E"];
    timeLB.textAlignment = NSTextAlignmentLeft;
    authorLB.text = @"00:25";
    self.timeLB = timeLB;
    [self.contentView addSubview:timeLB];
    
    UIImageView *selectImg = [[UIImageView alloc] initWithImage:GetImgWithStr(@"edit_默认")];
    self.selectImg = selectImg;
    [self.contentView addSubview:selectImg];
    
    UIView *line = [UIView new];
    line.backgroundColor = [UIColor colorWithHexString:@"#E6E6E6"];
    [self.contentView addSubview:line];
    
    [coverImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.contentView);
        make.leading.mas_equalTo(self.contentView.mas_leading).mas_offset(12 * scaleWidth);
        make.size.mas_equalTo(CGSizeMake(75 * scaleWidth, 75 * scaleHeight));
    }];
    
    [playbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.mas_equalTo(coverImg);
        make.size.mas_equalTo(CGSizeMake(34 * scaleWidth, 38 * scaleHeight));
    }];
    
    [titleLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.coverImg.mas_trailing).mas_offset(17 * scaleWidth);
        make.top.mas_equalTo(self.contentView.mas_top).mas_offset(16 * scaleHeight);
    }];
    
    [authorLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.titleLB);
        make.top.mas_equalTo(self.titleLB.mas_bottom).mas_offset(7 * scaleHeight);
    }];
    
    [timeLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.titleLB);
        make.bottom.mas_equalTo(self.contentView.mas_bottom).mas_offset(-16 * scaleHeight);
    }];
    
    [selectImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.contentView);
        make.trailing.mas_equalTo(self.contentView.mas_trailing).mas_offset(-22 * scaleWidth);
        make.size.mas_equalTo(CGSizeMake(18 * scaleWidth, 18 * scaleHeight));
    }];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.mas_equalTo(self.contentView);
        make.height.mas_equalTo(1 * scaleHeight);
    }];
    
}

#pragma mark 播放事件
- (void)playbtnAction:(UIButton *)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Hear_AddSoundViewCell" object:self];
}

#pragma mark 赋值
- (void)setModel:(Hear_MusicListModel *)model {
    _model = model;
    
    [self.coverImg sd_setImageWithURL:GetUrlWithStr(model.SongCover)];
    
    self.titleLB.text = model.SongName;
    
    self.authorLB.text = model.SingerName;
    
    NSInteger time = [model.SongLength integerValue];
    self.timeLB.text = [NSString stringWithFormat:@"%ld:%ld", time / 60, time %60];
    
    if (self.isSelect) {
        self.selectImg.image = GetImgWithStr(@"edit_选中");
        [self.playbtn setImage:GetImgWithStr(@"edit_暂停") forState:UIControlStateNormal];
        
        [MBProgressHUD showHUDAddedTo:WINDOW animated:YES];
        
        [self.item removeObserver:self forKeyPath:@"status"];
        [self.item removeObserver:self forKeyPath:@"loadedTimeRanges"];
        [self.item removeObserver:self forKeyPath:@"playbackBufferEmpty"];
        [self.item removeObserver:self forKeyPath:@"playbackLikelyToKeepUp"];
        
        self.item = [[AVPlayerItem alloc] initWithURL:GetUrlWithStr(model.SongLink)];
        
        [self.item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
        [self.item addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
        // 缓冲区空了，需要等待数据
        [self.item addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil];
        // 缓冲区有足够数据可以播放了
        [self.item addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil];
        
        self.player = [[AVPlayer alloc] initWithPlayerItem:self.item];
        
    } else {
        self.selectImg.image = GetImgWithStr(@"edit_默认");
        [self.playbtn setImage:GetImgWithStr(@"edit_播放") forState:UIControlStateNormal];
        
//        if (self.isPause) {
//            [self.player pause];
//        } else {
            [self.player replaceCurrentItemWithPlayerItem:nil];
            self.player = nil;
//        }
        
    }
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if (object == self.player.currentItem) {
        if ([keyPath isEqualToString:@"status"]) {
            
            if (self.player.currentItem.status == AVPlayerItemStatusReadyToPlay){
                if (self.isSelect) {
                    [MBProgressHUD hideHUDForView:WINDOW animated:YES];
                    [self.player play];
                } else {
                    [self.player pause];
                }
            } else if (self.player.currentItem.status == AVPlayerItemStatusFailed) {
                NSLog(@"播放失败");
            }
            
        } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
            [MBProgressHUD hideHUDForView:WINDOW animated:YES];
            // 计算缓冲进度
            NSTimeInterval timeInterval = [self availableDuration];
            CMTime duration             = self.item.duration;
            CGFloat totalDuration       = CMTimeGetSeconds(duration);
            
            DDLog(@"缓冲进度:>>>>>%f", timeInterval / totalDuration);
            
        } else if ([keyPath isEqualToString:@"playbackBufferEmpty"]) {
            [MBProgressHUD hideHUDForView:WINDOW animated:YES];
            // 当缓冲是空的时候
            if (self.item.playbackBufferEmpty) {
                [self.player pause];
            }
            
        } else if ([keyPath isEqualToString:@"playbackLikelyToKeepUp"]) {
            [MBProgressHUD hideHUDForView:WINDOW animated:YES];
            // 当缓冲好的时候
            if (self.item.playbackLikelyToKeepUp && self.player.currentItem.status == AVPlayerItemStatusReadyToPlay) {
                if (self.isSelect) {
                    [self.player play];
                }
            }
        }
    }
}

- (void)Hear_AddSoundViewControllerAction {
    [self.player pause];
}

- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
    CMTimeRange timeRange     = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds        = CMTimeGetSeconds(timeRange.start);
    float durationSeconds     = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result     = startSeconds + durationSeconds;// 计算缓冲总进度
    return result;
}

- (void)dealloc {
    [self.item removeObserver:self forKeyPath:@"status"];
    [self.item removeObserver:self forKeyPath:@"loadedTimeRanges"];
    [self.item removeObserver:self forKeyPath:@"playbackBufferEmpty"];
    [self.item removeObserver:self forKeyPath:@"playbackLikelyToKeepUp"];
}

@end
